package com.sch.hsy.web.controller.system;

import com.sch.hsy.common.constant.UserConstants;
import com.sch.hsy.common.core.controller.BaseController;
import com.sch.hsy.common.core.domain.AjaxResult;
import com.sch.hsy.common.core.domain.entity.SysBook;
import com.sch.hsy.common.core.domain.entity.SysDept;
import com.sch.hsy.common.core.domain.entity.SysUser;
import com.sch.hsy.common.utils.ShiroUtils;
import com.sch.hsy.common.utils.StringUtils;
import com.sch.hsy.framework.shiro.service.SysPasswordService;
import com.sch.hsy.system.domain.SysClassRanking;
import com.sch.hsy.system.domain.SysQues;
import com.sch.hsy.system.domain.SysRead;
import com.sch.hsy.system.service.*;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/app")
public class SysAppController extends BaseController {

    @Autowired
    ISysDeptService deptService;

    @Autowired
    ISysUserService userService;

    @Autowired
    ISysBookService bookService;

    @Autowired
    ISysChapterService chapterService;

    @Autowired
    ISysReadService readService;

    @Autowired
    ISysQuesService quesService;

    @Autowired
    private SysPasswordService passwordService;

    @PostMapping("/login")
    @ResponseBody
    public AjaxResult ajaxLogin(String username, String password)
    {
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        try
        {
            subject.login(token);
            SysUser sysUser = (SysUser) subject.getPrincipal();
            return AjaxResult.success(sysUser);
        }
        catch (AuthenticationException e)
        {
            String msg = "用户或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage()))
            {
                msg = e.getMessage();
            }
            return error(msg);
        }
    }

    @ApiOperation("注册")
    @PostMapping("/register")
    @ResponseBody
    public AjaxResult register(SysUser user){
        if (UserConstants.USER_NAME_NOT_UNIQUE.equals(userService.checkLoginNameUnique(user.getLoginName())))
        {
            return error("新增用户'" + user.getLoginName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return error("新增用户'" + user.getLoginName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            return error("新增用户'" + user.getLoginName() + "'失败，邮箱账号已存在");
        }
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
        if(user.getRoleIds() == null){
            user.setRoleIds(new Long[]{100L});
        }
        return toAjax(userService.insertUser(user));
    }

    @ApiOperation("修改密码")
    @PostMapping("/resetPassword")
    @ResponseBody
    public AjaxResult resetPassword(Long userId, String oldPassword, String newPassword){
        //获取用户信息
        SysUser sysUser = userService.selectUserById(userId);
        if(sysUser == null){
            return AjaxResult.error("用户不存在");
        }
        //对旧密码进行加盐
        String oldPsd = passwordService.encryptPassword(sysUser.getLoginName(), sysUser.getPassword(), sysUser.getSalt());
        if(!oldPsd.equals(oldPassword)){
            return AjaxResult.error("旧密码错误");
        }
        //对新密码加盐
        String newPsd = passwordService.encryptPassword(sysUser.getLoginName(), newPassword, sysUser.getSalt());
        sysUser.setPassword(newPsd);
        if (userService.resetUserPwd(sysUser) > 0){
            return AjaxResult.success("密码修改成功");
        }
        return AjaxResult.error("密码修改失败");

    }

    @ApiOperation("获取用户信息")
    @GetMapping("/getUserInfo")
    @ResponseBody
    public AjaxResult getUserInfo(Long userId){
        return AjaxResult.success(userService.selectUserById(userId));
    }

    @ApiOperation("获取班级")
    @GetMapping("/selectDept")
    @ResponseBody
    public AjaxResult selectDept(SysDept sysDept){
        return AjaxResult.success(deptService.selectDeptList(sysDept));
    }

    @ApiOperation("获取书籍列表")
    @GetMapping("/selectBookList")
    @ResponseBody
    public AjaxResult selectBookList(SysBook sysBook){
        return AjaxResult.success(bookService.selectBookList(sysBook));
    }

    @ApiOperation("根据书籍获取章节列表")
    @GetMapping("/selectChapterByBookId")
    @ResponseBody
    public AjaxResult selectChapterByBookId(Long bookId){
        return AjaxResult.success(chapterService.selectChapterList(bookId));
    }

    @ApiOperation("获取章节列表以及用户阅读进度")
    @GetMapping("/selectChapterRecordList")
    @ResponseBody
    public AjaxResult selectChapterRecordList(Long userId, Long bookId, Long chapterId){
        return AjaxResult.success(chapterService.selectChapterRecordList(userId, bookId, chapterId));
    }

    @ApiOperation("根据章节获取知识问答列表")
    @GetMapping("/selectQuesList")
    @ResponseBody
    public AjaxResult selectQuesList(Long chapterId){
        SysQues sysQues = new SysQues();
        sysQues.setChapterId(chapterId);
        return AjaxResult.success(quesService.selectQuesList(sysQues));
    }

    @ApiOperation("查询阅读积分列表")
    @GetMapping("/selectReadList")
    @ResponseBody
    public AjaxResult selectReadList(SysRead sysRead){
        return AjaxResult.success(readService.selectReadList(sysRead));
    }

    @ApiOperation("登记阅读状态")
    @PostMapping("/insertOrUpdateReadRecord")
    @ResponseBody
    public AjaxResult insertOrUpdateReadRecord(SysRead sysRead){
        List<SysRead> list = readService.selectReadList(sysRead);
        if(list.size() > 0){
            return AjaxResult.success(readService.updateRead(sysRead));
        }else{
            return AjaxResult.success(readService.insertRead(sysRead));
        }
    }

    @ApiOperation("查询积分排名")
    @GetMapping("/selectReadRankingList")
    @ResponseBody
    public AjaxResult selectReadRankingList(){
        return AjaxResult.success(readService.selectReadRankingList());
    }

    @ApiOperation("获取班级阅读进度排名")
    @GetMapping("/getReadRankingByClass")
    @ResponseBody
    public AjaxResult getReadRankingByClass(){
        //获取用户乘以总章节
        Long totalCount = chapterService.selectChaptersWithUsers();
        //获取班级阅读章节数
        List<Map<String, Object>> classReads = readService.selectReadRankingByClass();
        SysClassRanking sysClassRanking = new SysClassRanking();
        sysClassRanking.setTotalCount(totalCount);
        sysClassRanking.setRankings(classReads);
        return AjaxResult.success(sysClassRanking);
    }
}
